import logging

from flask import Blueprint, request
from app import app
from app.util.result import Result
from app.service.house_service import HouseService
from app.service.upload_service import UploadService

"""
房屋模块路由定义，该模块处理所有与房屋相关的HTTP请求
"""

# 创建房屋模块的蓝图
house_bp = Blueprint('house', __name__)

@house_bp.route('/getHouseList', methods=['GET'])
def get_house_list():
    """
    获取房屋列表接口
    Query Parameters:
        - page: 页码（默认1）
        - size: 每页数量（默认12）
        - order: 排序方式（0默认，1价格降序，2价格升序，3面积降序）非必须
        - title: 模糊匹配 非必须
        - status: 房屋状态 非必须
        - landlordName: 房东姓名 非必须
    Returns:
        - 成功: {"code": 1, "message": "success", "data": 房屋列表}
    """
    data = request.args
    return Result.success(data=HouseService.get_house_list(data))

@house_bp.route('/getHouseByLandlord', methods=['GET'])
def get_house_by_landlord():
    """
    获取房东发布的房屋列表接口
    Headers:
        - Authorization: JWT令牌
    Returns:
        - 成功: {"code": 1, "message": "success", "data": 房屋列表}
    """
    uid = app.payload['id']
    return Result.success(data=HouseService.get_house_by_landlord(uid))

@house_bp.route('/uploadHouseImg', methods=['POST'])
def upload_house_image():
    """
    上传房屋图片接口
    Request Body:
        - file: 图片文件
    Returns:
        - 成功: {"code": 1, "message": "success", "data": {"url": 图片URL}}
        - 失败: {"code": 0, "message": "上传失败"}
    """
    res = UploadService.upload(request.files)
    if res:
        return Result.success(data={
            'url': res
        })
    else:
        return Result.fail(message="上传失败")

@house_bp.route('/addHouse', methods=['POST'])
def add_house():
    """
    添加新房屋接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - title: 房屋标题
        - price: 价格
        - houseType: 房屋类型
        - area: 面积
        - city: 城市
        - district: 区域
        - detailed_address: 详细地址
        - images: 图片列表
        - keywords: 关键词列表
        - deposit: 押金
    Returns:
        - 成功: {"code": 1, "message": "success"}
        - 失败: {"code": 0, "message": "添加失败"}
    """
    uid = app.payload['id']
    add_house_data = request.get_json()
    return Result.success() if HouseService.add_house(add_house_data, uid) else Result.fail(message="添加失败")

@house_bp.route('/deleteHouse', methods=['DELETE'])
def delete_house():
    """
    删除房屋接口
    Headers:
        - Authorization: JWT令牌
    Query Parameters:
        - id: 房屋ID
    Returns:
        - 成功: {"code": 1, "message": "success"}
        - 失败: {"code": 0, "message": "删除失败"}
    """
    uid = app.payload['id']
    house_id = request.args.get('id')
    return Result.success() if HouseService.delete_house(uid, house_id) else Result.fail(message="删除失败")

@house_bp.route('/updateHouse', methods=['PUT'])
def update_house():
    """
    更新房屋信息接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - id: 房屋ID
        - title: 房屋标题
        - price: 价格
        - houseType: 房屋类型
        - area: 面积
        - city: 城市
        - district: 区域
        - detailed_address: 详细地址
        - images: 图片列表
        - keywords: 关键词列表
        - deposit: 押金
    Returns:
        - 成功: {"code": 1, "message": "success"}
        - 失败: {"code": 0, "message": "修改失败"}
    """
    uid = app.payload['id']
    update_house_data = request.get_json()
    return Result.success() if HouseService.update_house(update_house_data, uid) else Result.fail(message="修改失败")

@house_bp.route('/updateStatus', methods=['PUT'])
def update_status():
    """
    更新房屋状态接口
    Headers:
        - Authorization: JWT令牌
    Request Body:
        - id: 房屋ID
        - status: 新状态
    Returns:
        - 成功: {"code": 1, "message": "success"}
        - 失败: {"code": 0, "message": "更新状态失败"}
    """
    uid = app.payload['id']
    data = request.get_json()
    return Result.success() if HouseService.update_house_status(data, uid) else Result.fail(message="更新状态失败")


@house_bp.route('/searchresult', methods=['get'])
def search_result():
    """
     获取房屋列表接口
    Query Parameters:
       -:keyword :搜索关键字
       -:houseType:户型
       -:rentType:租赁方式
       -:region: 地区
       -:minPrice:最低价格
       -：maxPrice:最高价格
    Returns:
        - 成功: {"code": 1, "message": "success", "data": 房屋列表}
    :return:
    """
    data = request.args

    #logging.info("筛选数据：%s", data)  # 使用 %s 格式化数据
    return Result.success(data=HouseService.get_search_result(data))